<?php

namespace App\Model\Member;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Member extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'member';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     *
     * 根据用户ID拉取商户信息
     *
     * @param $id
     * @return mixed
     */
    public static function getStore($id)
    {
        $user = self::find($id);
        $store = Store::find($user->store_id);
        return $store;
    }
    

    /**
     *
     * 用户使用余额
     *
     * @param $uid 用户ID
     * @param $price 使用余额数
     * @param $note 备注
     * @return bool
     */
    public static function subMoney($uid, $price, $note = null)
    {
        # 事务开始
        DB::beginTransaction();
        $user = self::find($uid);
        # 判断用户余额是否充足
        if(bccomp($user->money, $price) < 0) return false;
        # 减去用户余额
        $user->money -= $price;
        if(!$user->save()){
            DB::rollBack();
            return false;
        }
        # 写入余额操作日志
        $data = [
            'member_id' => $uid,
            'action' => 1,
            'number' => - $price,
            'note' => $note,
            'create_time' => currentTime(),
        ];
        $result = UserMoney::insert($data);
        if(!$result){
            DB::rollBack();
            return false;
        }
        DB::commit();
        return true;
    }
}